package com.usian.comment.service.impl;

import com.baomidou.mybatisplus.extension.api.R;
import com.sun.xml.bind.v2.model.core.ID;
import com.usian.comment.feign.UserFeign;
import com.usian.comment.service.CommentService;
import com.usian.model.comment.dtos.ApCommentVo;
import com.usian.model.comment.dtos.CommentDto;
import com.usian.model.comment.dtos.CommentLikeDto;
import com.usian.model.comment.dtos.CommentSaveDto;
import com.usian.model.comment.pojos.ApComment;
import com.usian.model.comment.pojos.ApCommentLike;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Auther:ASS
 * @Date:2023/3/6 16:15
 */
@Service
public class CommentServiceImpl implements CommentService {


    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserFeign userFeign;

    /**
     * 保存评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {

        if (dto==null || dto.getArticleId()==null || StringUtils.isBlank(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //获取当前用户及详情
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApUser apUser1 = userFeign.findUserById(apUser.getId());
        if (apUser1!=null){
            ApComment apComment = new ApComment();
            apComment.setAuthorId(apUser.getId());
            apComment.setAuthorName(apUser1.getName());
            apComment.setContent(dto.getContent());
            apComment.setEntryId(dto.getArticleId());
            apComment.setCreatedTime(new Date());
            apComment.setUpdatedTime(new Date());
            apComment.setImage(apUser1.getImage());
            apComment.setLikes(0);
            apComment.setReply(0);
            apComment.setType((short) 0);
            apComment.setFlag((short) 0);
            mongoTemplate.insert(apComment);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 点赞某一条评论·
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDto dto) {
        //校验参数
        if (dto==null || StringUtils.isBlank(dto.getCommentId()) || dto.getOperation()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (apComment!=null) {
            //点赞 apcomment  like+1  insert到ApCommentLike表
            if (dto.getOperation() == 0) {
                Update update = new Update();
                update.set("likes", apComment.getLikes() + 1);
                mongoTemplate.upsert(Query.query(Criteria.where("id").is(dto.getCommentId())), update, ApComment.class);

                ApCommentLike apCommentLike = new ApCommentLike();
                apCommentLike.setAuthorId(apUser.getId());
                apCommentLike.setCommentId(apComment.getId());
                apCommentLike.setOperation(dto.getOperation());
                mongoTemplate.insert(apCommentLike);


            } else if (dto.getOperation() == 1) {
                //取消点赞 apcomment  like-1  remove到ApCommentLike表
                Update update = new Update();
                update.set("likes", apComment.getLikes() <= 0 ? 0 : apComment.getLikes() - 1);
                mongoTemplate.upsert(Query.query(Criteria.where("id").is(dto.getCommentId())), update, ApComment.class);

                mongoTemplate.remove(Query.query(Criteria.where("authorId").is(apUser.getId()).and("commentId")
                        .is(dto.getCommentId())), ApCommentLike.class);

            }
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //返回 like 数量
        Map<String,Object> result=new HashMap<>();
        ApComment apComment1 = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        result.put("likes",apComment1.getLikes());
        return ResponseResult.okResult(result);
    }




    /**
     * 查询评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findByArticleId(CommentDto dto) {
        if (dto.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //按照文章id进行过滤设置分页和排序

        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("createdTime").lt(dto.getMinDate()));
        query.limit(5).with(Sort.by(Sort.Direction.DESC,"createdTime"));

        List<ApComment> list = mongoTemplate.find(query, ApComment.class);


        //数据封装返回
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }


        //用户已登录，加载数据，需要判断当前用户点赞了哪些、
        List<String> idList = list.stream().map(x -> x.getId()).collect(Collectors.toList());
        Query query1 = Query.query(Criteria.where("commentId").in(idList).and("authorId").is(apUser.getId()));
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(query1, ApCommentLike.class);

        List<ApCommentVo> resultList = new ArrayList<>();

        if(list!=null && apCommentLikes!=null){
            //双层
            list.stream().forEach(x -> {
                ApCommentVo apCommentVo = new ApCommentVo();
                BeanUtils.copyProperties(x, apCommentVo);
                for (ApCommentLike apCommentLike : apCommentLikes) {
                    if (x.getId().equals(apCommentLike.getCommentId())) {
                        apCommentVo.setOperation((short) 0);

                        //查出来点赞的数量
                        break;
                    }
                }
                resultList.add(apCommentVo);
            });
            return ResponseResult.okResult(resultList);
        }else {
            return ResponseResult.okResult(list);
        }
    }
}
